<template>
  <div class="add-select">
    <el-dialog
      ref="dialog"
      title="新增产品"
      :visible.sync="dialogShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="800"
      @close="closeDialog"
    >
      <div>
        <search-form
          ref="searchForm"
          :search-config="searchConfig"
          :label-width="100"
          @clear="handleClear"
          @search="handleSearch"
        />
        <!-- @clear="clearSearch" -->

      </div>
      <el-tabs v-model="activeName" @tab-click="changeTab">
        <el-tab-pane label="全部" name="all">
          <div class="table-list-box">
            <el-table
              ref="multipleTable"
              v-loading="tableLoading"
              :data="tableData"
              border
              max-height="220"
              header-row-class-name="table-list-header"
              tooltip-effect="dark"
              style="width: 100%"
              :row-class-name="tableRowClassName"
              @row-click="selectRow"
              @select="selectTable"
              @select-all="selectionAll"
            >
              <!-- @selection-change="selectChange" -->

              <el-table-column type="selection" width="55" />
              <el-table-column prop="productCode" label="产品编码" width="120" show-overflow-tooltip />
              <el-table-column prop="productName" label="产品描述" width="120" show-overflow-tooltip />
              <el-table-column prop="prodModelName" label="型号" width="120" show-overflow-tooltip />
              <el-table-column prop="productCategoryName" label="品类" width="100" show-overflow-tooltip />
              <el-table-column prop="saleSeriesName" label="产品系列" width="120" show-overflow-tooltip />
              <!-- <el-table-column prop="proPosition" label="产品定位" width="120" /> -->
            </el-table>
          </div>
          <div class="pagination-box">
            <div class="pagination-container">
              <el-pagination
                :current-page.sync="currentPage"
                :page-sizes="pageSizelist"
                :page-size="pageSize"
                layout="sizes, prev, pager, next, slot"
                :total="allTotal === 0 ? total : allTotal"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
                <span class="el-pagination__jump">前往
                  <el-input-number
                    v-model="jumpPage"
                    :controls="false"
                    :min="1"
                    @blur="showEnter"
                    @keyup.enter.native="showEnter"
                  />页</span>
              </el-pagination>
              <div v-show="total <= pageSize" class="pagination-info">当前显示
                <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
                <span class="total"> {{ tableData.length }} </span> 条记录
              </div>
              <div v-show="total > pageSize" class="pagination-info">当前显示
                <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
                <span :class="[allTotal === 0 && total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && total !== 0 ? total-1 +'+': allTotal }}  </span> 条记录
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`已选择(${selectedData.length})`" name="selected">
          <div class="table-list-box">
            <el-table
              ref="chosenTable"
              :data="showSelectedData"
              border
              max-height="220"
              header-row-class-name="table-list-header"
              highlight-current-row
              tooltip-effect="dark"
              style="width: 100%"
            >
              <el-table-column prop="productCode" label="产品编码" width="120" show-overflow-tooltip />
              <el-table-column prop="productName" label="产品描述" width="120" show-overflow-tooltip />
              <el-table-column prop="prodModelName" label="型号" width="120" show-overflow-tooltip />
              <el-table-column prop="productCategoryName" label="品类" width="100" show-overflow-tooltip />
              <el-table-column prop="saleSeriesName" label="产品系列" width="120" show-overflow-tooltip />
              <el-table-column label="操作" width="60">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    style="color:#3dc094; cursor: pointer;"
                    @click="deleteChose(scope.$index,scope.row)"
                  >删 除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- <div style="margin:10px 0;display:inlnk-black;font-size: 14px;">已选择
        <span style="color:#0f3eea;">{{ selectedData.length }}</span>条数据
      </div> -->

      <div slot="footer">
        <el-button size="mini" @click="closeDialog">取消</el-button>
        <el-button type="primary" size="mini" @click="submitData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryProData } from '@/api/proConfig'
export default {
  name: 'AddProduct',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      activeName: 'all',
      showSelectedData: [],
      otherFilters: [
        { 'id': 'proState', 'property': 'proState', 'operator': '=', 'value': 'E' },
        { 'id': 'status', 'property': 'status', 'operator': '=', 'value': '1' }
      ],
      secondOtherFilter: [],
      tableLoading: false,
      searchConfig: [
        { label: '产品编码', prop: 'productCode', type: 'text', value: '', placeholder: '' },
        { label: '产品描述', prop: 'productName', type: 'text', value: '', placeholder: '', single: true },
        {
          label: '型号',
          prop: 'prodModelCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `/select-service/api/v1/productModel/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name', // productSaleSeriesName
              value: 'code' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '型号',
            interfacePath: '/select-service/api/v1/productModel/page',
            setting: [
              { prop: 'code', title: '系列编码' },
              { prop: 'name', title: '系列名称' }
            ]
          }
        },
        {
          label: '品类',
          prop: 'productCategoryCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `/select-service/api/v1/productCategory/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name', // productSaleSeriesName
              value: 'code' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '品类',
            interfacePath: '/select-service/api/v1/productCategory/page',
            setting: [
              { prop: 'code', title: '系列编码' },
              { prop: 'name', title: '系列名称' }
            ]
          }
        },
        {
          label: '产品系列',
          prop: 'saleSeriesCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `/select-service/api/v1/productSaleSeries/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name', // productSaleSeriesName
              value: 'code' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '系列',
            interfacePath: '/select-service/api/v1/productSaleSeries/page',
            setting: [
              { prop: 'code', title: '系列编码' },
              { prop: 'name', title: '系列名称' }
            ]
          }
        }
      ],
      pageSize: 5,
      pageSizelist: [5, 10, 15, 20],
      currentPage: 1,
      total: '',
      jumpPage: '',
      allTotal: 0,
      filtersRaw: {}, // 全局搜索条件
      selectedData: [],
      tableData: [],
      proCodeList: []
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.selectedData = []
          this.$nextTick(() => {
            this.$refs.multipleTable.clearSelection()
          })
        }
      }
    }
  },
  created() {
    if (this.detailData.otherFilters) {
      this.secondOtherFilter = this.detailData.otherFilters
      this.proCodeList = this.secondOtherFilter.map(item => item.productCode)
    }
    this.getProductData(this.currentPage, this.pageSize, false, this.proCodeList)
  },
  methods: {
    handleClear() {
      this.filtersRaw = []
    },
    // 获取搜索条件
    handleSearch(data) {
      this.currentPage = 1
      this.pageSize = 5
      if (this.activeName === 'all') {
        this.onParams(data)
      } else {
        if (!this.selectedData.length) return
        if (data.filtersRaw && data.filtersRaw.length) {
          const arr = []
          this.selectedData.forEach(item => {
            const productCodeList = data.filtersRaw.filter(item => item.property === 'productCode')
            const productNameList = data.filtersRaw.filter(item => item.property === 'productName')
            const productModelList = data.filtersRaw.filter(item => item.property === 'prodModelCode')
            const saleSeriesList = data.filtersRaw.filter(item => item.property === 'saleSeriesCode')
            const categoryList = data.filtersRaw.filter(item => item.property === 'productCategoryCode')
            let flag1 = true
            let flag2 = true
            let flag3 = true
            let flag4 = true
            let flag5 = true
            if (productCodeList.length) {
              if (productCodeList[0].operator === 'like') {
                flag1 = (item.productCode.search(productCodeList[0].value) !== -1)
              } else {
                const proCode = JSON.parse(productCodeList[0].value)
                flag1 = proCode.includes(Number(item.productCode))
              }
            }
            if (productNameList.length) {
              flag2 = (item.productName.search(productNameList[0].value) !== -1)
            }
            if (productModelList.length) {
              flag3 = (item.prodModelCode === productModelList[0].value)
            }
            if (saleSeriesList.length) {
              flag4 = (item.saleSeriesCode === saleSeriesList[0].value)
            }
            if (categoryList.length) {
              flag5 = (item.productCategoryCode === categoryList[0].value)
            }
            if (flag1 && flag2 && flag3 && flag4 && flag5) {
              arr.push(item)
            }
          })
          this.showSelectedData = arr
        } else {
          this.showSelectedData = this.selectedData
        }
      }
    },
    getProductData(page, rows, onlyCountFlag, otherFilter) {
      this.tableLoading = true
      let filtersRaw = []
      if (otherFilter.length) {
        const filters = '[' + otherFilter.join(',') + ']'
        filtersRaw = [{ 'id': 'productCode', 'property': 'productCode', 'operator': 'not in', 'value': filters }]
      }
      // let allOtherFilter = [...this.otherFilters]
      // if (filtersRaw.length) {
      const allOtherFilter = [...this.otherFilters, ...filtersRaw, ...this.filtersRaw.filtersRaw]
      // }
      // return
      const dataForm = new FormData()
      dataForm.append('page', page)
      dataForm.append('rows', rows)
      dataForm.append('onlyCountFlag', onlyCountFlag)
      dataForm.append('filtersRaw', JSON.stringify(allOtherFilter))
      queryProData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          if (!onlyCountFlag) {
            this.tableData = res.data.records
            this.total = res.data.total
            if (this.total <= this.currentPage * this.pageSize) {
              this.allTotal = this.total
            }
            const selectIds = this.selectedData.map(e => {
              return e.productCode
            })
            // 表格数据对比是否存在已选择数据并对其勾选
            this.tableData.forEach(item => {
              if (selectIds.includes(item.productCode)) {
                this.$nextTick(() => {
                  this.$refs.multipleTable.toggleRowSelection(item)
                })
              }
            })
          } else {
            this.allTotal = res.data.total
            this.total = res.data.total
            this.currentPage = res.data.page
          }
        }
        this.showSelectedData = this.selectedData
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    onParams(data) {
      this.filtersRaw = data
      this.tableLoading = true
      let filtersRaw = []
      if (this.proCodeList.length) {
        const filters = '[' + this.proCodeList.join(',') + ']'
        filtersRaw = [{ 'id': 'productCode', 'property': 'productCode', 'operator': 'not in', 'value': filters }]
      }
      const dataFilters = [...data.filtersRaw, ...filtersRaw, ...this.otherFilters]
      const dataForm = new FormData()
      dataForm.append('page', 1)
      dataForm.append('rows', this.pageSize)
      dataForm.append('onlyCountFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(dataFilters))
      queryProData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          this.tableData = res.data.records
          this.total = res.data.total
          if (this.total <= this.currentPage * this.pageSize) {
            this.allTotal = this.total
          }
          const selectIds = this.selectedData.map(e => {
            return e.productCode
          })
          // 表格数据对比是否存在已选择数据并对其勾选
          this.tableData.forEach(item => {
            if (selectIds.includes(item.productCode)) {
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(item)
              })
            }
          })
        }
        this.showSelectedData = this.selectedData
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      this.jumpPage = currentPage
      this.currentPage = currentPage
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.getProductData(this.currentPage, this.pageSize, false, this.proCodeList)
    },
    // 分页数据获取---> this.$refs.chosenTable/multipleTable.clearSelection
    handleSizeChange(val) {
      this.pageSize = val
      this.$refs.multipleTable.clearSelection()
      this.$refs.chosenTable.clearSelection()
      this.jumpToFirstPage()
      this.getProductData(this.currentPage, this.pageSize, false, this.proCodeList)
    },
    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage
      const pageRange = `${start}-${end}`
      return pageRange
    },
    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.currentPage
      if (val) {
        page = val
      }
      this.getProductData(page, this.pageSize, true, this.proCodeList)
      this.$nextTick(() => {
        this.getProductData(page, this.pageSize, false, this.proCodeList)
      })
    },
    setTBIndex({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex
    },
    // // 勾选
    // selectionChange(selection) {
    //   this.selections = selection
    // },
    selectionAll(val) {
      const selectIds = this.selectedData.map(e => {
        return e.productCode
      })
      val.length &&
        val.forEach(item => {
          if (!selectIds.includes(item.productCode)) {
            this.selectedData = this.selectedData.concat(item)
          }
        })
      if (!val.length) {
        this.tableData.forEach(item => {
          this.selectedData.forEach((s, index) => {
            if (s.productCode === item.productCode) {
              this.selectedData.splice(index, 1)
            }
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    // 产品数据手动勾选
    selectTable(val, row) {
      if (this.selectedData.length > 0) {
        // 筛选已勾选的code
        const codeList = val.map(e => {
          return e.productCode
        })
        if (codeList.includes(row.productCode)) {
          // 判断是勾选还是取消
          this.selectedData = this.selectedData.concat(row)
        } else {
          this.selectedData.forEach((item, index) => {
            if (item.productCode === row.productCode) {
              this.selectedData.splice(index, 1)
            }
          })
        }
      } else {
        this.selectedData = val
      }
      this.showSelectedData = this.selectedData
      this.$nextTick(() => {
        this.selectedData.forEach(item => {
          this.$refs.chosenTable.toggleRowSelection(item, true)
        })
      })
    },
    // 产品数据手动勾选
    selectRow(row) {
      if (this.selectedData.length > 0) {
        const arr = JSON.parse(JSON.stringify(this.selectedData))
        // 筛选已勾选的code
        const codeList = arr.map(e => {
          return e.productCode
        })
        if (!codeList.includes(row.productCode)) {
          // 判断是勾选还是取消
          this.selectedData = arr.concat(row)
          this.$nextTick(() => {
            this.selectedData.forEach(item => {
              this.$refs.multipleTable.toggleRowSelection(item, true)
            })
          })
        } else {
          this.selectedData.forEach(item => {
            if (item.productCode === row.productCode) {
              this.$refs.multipleTable.toggleRowSelection(item, false)
            }
          })
          this.$nextTick(() => {
            this.selectedData.forEach((item, index) => {
              if (item.productCode === row.productCode) {
                this.selectedData.splice(index, 1)
              }
            })
          })
        }
      } else {
        this.selectedData.push(row)
        this.$nextTick(() => {
          this.selectedData.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        })
      }
      this.showSelectedData = this.selectedData
    },
    deleteChose(index, row) {
      this.selectedData.splice(index, 1)
      this.$nextTick(() => {
        this.tableData.forEach(e => {
          if (e.productCode === row.productCode) {
            this.$refs.multipleTable.toggleRowSelection(e, false)
          }
        })
      })
      this.showSelectedData = this.selectedData
    },
    closeDialog() {
      this.dialogShow = false
    },
    submitData() {
      if (!this.selectedData.length) {
        this.$message.warning('请勾选产品')
        return
      }
      this.$emit('success', this.selectedData)
      this.dialogShow = false
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedData.filter(item => row.productCode === item.productCode)
      return (filterArr.length > 0) ? 'selected-highlight' : ''
    },
    changeTab(tab) {
      this.$refs.searchForm.handleSearch()
    }
  }
}
</script>
<style lang="scss" scoped>
.add-select{
  display: inline-block;
  .dialog-body{
    margin-top: -20px;
  }
}
</style>
